require 'date'

# Make sure our template can use <%=h
helpers do
  include Rack::Utils
  alias_method :h, :escape_html

  def nl2br(str)
    str.gsub("\n", '<br />')
  end

  def hn(str)
    nl2br(ERB::Util.h(str))
  end

  def rails_like_params(params)
    new_params = {}
    params.each_pair do |full_key, value|
      this_param = new_params
      split_keys = full_key.split(/\]\[|\]|\[/)
      split_keys.each_index do |index|
        break if split_keys.length == index + 1
        this_param[split_keys[index]] ||= {}
        this_param = this_param[split_keys[index]]
     end
     this_param[split_keys.last] = value
    end
    return new_params
  end

  def rails_like_request_start_log(request)
    @request_start_time = Time.now
    logs = []
    now = DateTime.now.strftime("%Y-%m-%d %H:%M:%S")
    logs << ""
    logs << "Processing #{request.fullpath()} (for #{request.host}:#{request.port} at #{now}) [#{request.request_method()}]"
    logs << '  Parameters (before routing): ' + request.params.inspect
    return logs.join("\n")
  end

  def rails_like_parameter_log(params)
    return '  Parameters (after routing): ' + params.inspect
  end

  def rails_like_request_end_logging(request, response)
    logs = []
    logs << "Redirected to #{response.location()}" if response.redirect?()
    response_time = "???"
    unless @request_start_time
      exec_time = Time.now - @request_start_time
      response_time = (1000 * exec_time.to_f).to_s
    end
    logs << "Completed in #{response_time}ms | #{response.status} Found [#{request.fullpath()}]"
    @logger.debug  logs.join("\n")
  end

  def flash_manager
    
  end

  def included_notice?(flash)
    not (flash.nil? or flash[:notice].nil?)
  end

  def included_error?(flash)
    not (flash.nil? or flash[:error].nil?)
  end

  def included_error_message?(dm_array)
    included = false
    for dm in dm_array do
      next if dm.nil?
      included = true unless dm.valid?
    end
    return included
  end

  def put_error_messages(dm_array)
    error_message = ''
    for dm in dm_array do
      next if dm.nil?
      unless dm.valid?
        dm.errors.each do |e|
          error_message << e
        end
      end
    end
  end

  def options_for_select(options, selected)
    option_array = []
    for option in options
      if selected == option[1]
        option_array << '<option value="' + h(option[1].to_s) + '" selected="selected">' + h(option[0].to_s) + '</option>'
      else
        option_array << '<option value="' + h(option[1].to_s) + '">' + h(option[0].to_s) + '</option>'
      end
    end
    return option_array.join("\n")
  end

  def cycle(case_false, case_true)
    @cycle_check_flag |= false
    if @cycle_check_flag
      @cycle_check_flag = false
      return case_true
    else
      @cycle_check_flag = true
      return case_false
    end
  end

  def came_stamp(came_at)
    return "-" if came_at.nil?
    return came_at.strftime("%Y/%m/%d %H:%M:%S")
  end

  def put_delete_java_script(message = 'Are you sure?')
    "if (confirm('#{message}')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;"
  end
end

